<template>
  <view class="">
    <picker :value="selIndex" @change="selectChange" :range="labelList">
      <!-- <view class="input-suffix">
        <view class="value-view">
          {{ showLabel || placeholder }}
        </view>

        <view class="row-suffix">
          <view class="image-content">
            <image v-if="img_url" :src="img_url + 'collapse.png'" />
          </view>
        </view>
      </view> -->
      <view>
        <slot :label="showLabel || placeholder" />
      </view>
    </picker>
  </view>
</template>

<script>
export default {
  props: {
    value: {
      type: [String | Number],
      default: '',
    },

    options: {
      type: Array,
      default: () => [
        {
          label: '233',
          value: '233',
        },
      ],
    },

    field: {
      type: Object,
      default: () => ({
        value: 'value',
        label: 'label',
      }),
    },

    placeholder: {
      type: String,
      default: '请选择',
    },
  },

  data() {
    return {
      labelList: [],
      valueList: [],
      showLabel: '',
      selIndex: ''
    };
  },

  methods: {
    init() {
      const {
        field: { value, label },
        value: v,
      } = this;
      console.log('sel 初始化--------', this.options);

      this.labelList = this.options.map((o) => o[label]);
      this.valueList = this.options.map((o) => o[value]);

      if (v != null) {
        const idx = this.valueList.find((o) => o === v);
        if (idx !== -1) {
          this.selIndex = idx;
          this.showLabel = this.labelList[idx];
        }
      }
    },

    selectChange(e) {
      const {
        detail: { value },
      } = e;
      this.setValue(value);
    },

    setValue(index) {
      const label = this.labelList[index];
      const value = this.valueList[index];

      this.showLabel = label;
      this.selIndex = index;
      this.$emit('update: value', value);
      this.$emit('change', {value, label})
    },
  },

  watch: {
    list: {
      immediate: true,
      handler: function () {
        this.init();
      },
    },
  },
};
</script>

<style lang="scss" scoped></style>
